
import time
import datetime
from datetime import datetime as datetime2
from datetime import timedelta
import urllib
import urllib2
import cookielib
import simplejson

API_URL = 'https://api.alertme.com/v5/'
COOKIEFILE = 'cookies.lwp'

cj = cookielib.LWPCookieJar()
urlopen = urllib2.urlopen
Request = urllib2.Request

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

def log_in(username, password):
    theurl = API_URL + 'login'
    txdata = urllib.urlencode({"username" : username, "password" : password})
    
    try:
        req = Request(theurl, txdata)
        handle = urlopen(req)
        read = handle.read()
        result = simplejson.loads(read)
        print "login: " + read
        
        if cj is None:
            print "no cookies"
        else:
            '''
            print 'cookies:'
            for index, cookie in enumerate(cj):
                print index, '  :  ', cookie
            '''
            cj.save(COOKIEFILE)
        return result
    
    except urllib2.HTTPError, he:
        print 'exception from request: ', theurl, he
        return False

def query_user_info(username):
    theurl = API_URL + 'users/' + username
    
    try:
        req = Request(theurl)
        handle = urlopen(req)
        read = handle.read()
        result = simplejson.loads(read)
        print "user info: " + read
        return result
    
    except urllib2.HTTPError, he:
        print 'exception from request: ', theurl, he
        return False

def query_hub(username):
    theurl = API_URL + 'users/' + username + '/hubs'
    
    try:
        req = Request(theurl)
        handle = urlopen(req)
        read = handle.read()
        result = simplejson.loads(read)
        print "user hubs: " + read
        return result
    
    except urllib2.HTTPError, he:
        print 'exception from request: ', theurl, he
        return False
    
def query_hub_info(username, hub_id):
    theurl = API_URL + 'users/' + username + '/hubs/' + hub_id
    
    try:
        req = Request(theurl)
        handle = urlopen(req)
        read = handle.read()
        result = simplejson.loads(read)
        print "hub info: " + read
        return result
    
    except urllib2.HTTPError, he:
        print 'exception from request: ', theurl, he
        return False

def query_hub_devices(username, hub_id):
    theurl = API_URL + 'users/' + username + '/hubs/' + hub_id + '/devices'
    
    try:
        req = Request(theurl)
        handle = urlopen(req)
        read = handle.read()
        result = simplejson.loads(read)
        print "hub devices: " + read
        return result
    
    except urllib2.HTTPError, he:
        print 'exception from request: ', theurl, he
        return False
    
def query_devices_channels(username, hub_id, device_type, device_id):
    theurl = API_URL + 'users/' + username + '/hubs/' + hub_id + '/devices/' + device_type + "/" + device_id + '/channels'
    
    try:
        req = Request(theurl)
        handle = urlopen(req)
        read = handle.read()
        result = simplejson.loads(read)
        print device_type + " channels: " + read
        return result
    
    except urllib2.HTTPError, he:
        print 'exception from request: ', theurl, he
        return False
    
def query_channel_data(username, hub_id, device_type, device_id, channel, start, end, interval, operation, file):
    theurl = API_URL + 'users/' + username + '/hubs/' + hub_id + '/devices/' + device_type + "/" + device_id + '/channels/' + channel
    theurl = theurl + '?start=' + start + '&end=' + end +'&interval=' + interval + '&operation=' + operation
    
    try:
        req = Request(theurl)
        handle = urlopen(req)
        read = handle.read()
        result = simplejson.loads(read)
        print " " + channel + " data: " + read
        write_json_to_csv(result, file)
        return result
    
    except urllib2.HTTPError, he:
        print " " + channel + " data: " + theurl, he
        return False
    
def write_json_to_csv(json, file):
    start = json['start']
    interval = json['interval']
    data = json['values']['average']
    for i in range(len(data)):
        timestamp = start + i*interval
        data_item = data[i]
        csv_line = str(timestamp) + ', ' + str(data_item) + '\n'
        file.write(csv_line)
    
OUTPUT_DIRECTORY = 'C:\\Users\\op106\\Documents\\0000\\'
#USERNAME = 'southamptonuni001'
#PASSWORD = 'secur1ty!'
#USERNAME = 'acr@ecs.soton.ac.uk'
#PASSWORD = 'OliverParson'
USERNAME = 'op106@ecs.soton.ac.uk'
PASSWORD = 'mariokart'
DOWNLOAD_INTERVAL = 2
DEVICE_CHANNELS = {
                   'MeterReader' : ['power'],#'signal', 'battery', 'temperature', 'power'],
                   'Lamp' : [],
                   'Button' : ['signal', 'battery', 'temperature'],
                   'Keyfob' : [],
                   'MotionSensor' : ['signal', 'battery', 'temperature'],
                   'ContactSensor' : ['signal', 'battery', 'temperature'],
                   'SmartPlug' : ['signal', 'battery', 'temperature', 'power'],
                   }
START = datetime2(2011,3,16,0,0,0)
END = datetime2(2011,3,17,0,0,0)
METERREADER_INTERVAL = '1'
SMARTPLUG_INTERVAL = '30'
DEFAULT_INTERVAL = '120'
OPERATION = 'average'

#perform log in and queries of user and hub
log_in_json = log_in(USERNAME, PASSWORD)
hub_id = str(log_in_json['hubIds'][0])
query_user_info(USERNAME)
query_hub(USERNAME)
query_hub_info(USERNAME, hub_id)
hub_devices = query_hub_devices(USERNAME, hub_id)

#iterate over devices
for device in hub_devices:
    device_type = device['type']
    device_id = device['id']
    if DEVICE_CHANNELS.keys().count(device_type):
        device_channels = query_devices_channels(USERNAME, hub_id, device_type, device_id)
        #iterate over channels
        for channel in device_channels:
            channel_name = channel['name']
            channel_has_current_value = channel['hasCurrentValue']
            channel_has_historical_values = channel['hasHistoricalValues']
            channel_has_future_values = channel['hasFutureValues']
            if DEVICE_CHANNELS[device_type].count(channel_name) and channel_has_historical_values:
                interval = None
                if device_type == 'MeterReader' and channel_name == 'power':
                    interval = METERREADER_INTERVAL
                elif device_type == 'SmartPlug' and channel_name == 'power':
                    interval = SMARTPLUG_INTERVAL
                else:
                    interval = DEFAULT_INTERVAL
                filename = USERNAME + '_' + device_type + '_' +  device_id + '_' + channel_name + '.csv'
                file = open(OUTPUT_DIRECTORY + filename, 'w')
                #iterate over subintervals
                for i in range(24/DOWNLOAD_INTERVAL):
                    temp_start = START + timedelta(hours=i*DOWNLOAD_INTERVAL)
                    temp_end = START + timedelta(hours=(i+1)*DOWNLOAD_INTERVAL) - timedelta(seconds=1)
                    start_string = str(int(time.mktime(temp_start.timetuple())))
                    end_string = str(int(time.mktime(temp_end.timetuple())))
                    historical_values = query_channel_data(USERNAME, hub_id, device_type, device_id, channel_name, start_string, end_string, interval, OPERATION, file)
                file.close()
